<!--公告清单-->
<template>
  <div>
    <div style="display: flex; max-height: 20px; margin-left: -20px">
      <h5 style="margin-left: 30px">项目编号</h5>
      <el-input style="margin-top: -5px; width:120px; margin-left: 10px" placeholder="请输入项目编号" v-model="projectNumber"></el-input>
      <h5 style="margin-left: 30px">项目名称</h5>
      <el-input style="margin-top: -5px; width:120px; margin-left: 10px" placeholder="请输入项目名称" v-model="projectName" ></el-input>
      <el-button type="primary" style="margin-top: -5px; margin-left: 30px" icon="el-icon-search" @click="init">查询</el-button>
      <el-button type="warning" style="margin-top: -5px; margin-left: 10px" icon="el-icon-refresh" @click="reset">重置</el-button>
    </div>
    <div style="display: flex;">
      <el-table :data="tableData" style="margin-top: 10px" height="500">
        <el-table-column fixed label="序号"  width="45">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="announcementName" label="公告名称" width="250"></el-table-column>
        <el-table-column prop="projectNumber" label="项目编号" width="100"></el-table-column>
        <el-table-column prop="projectName" label="项目名称" width="140"></el-table-column>
        <el-table-column prop="quantity" label="数量" width="45"></el-table-column>
        <el-table-column prop="budget" label="预算（万元）" width="100"></el-table-column>
        <el-table-column prop="projectType" label="项目类型" width="80"></el-table-column>
        <el-table-column prop="meetingRoom" label="会议室" width="100"></el-table-column>
        <el-table-column prop="announDate" label="公告时间" width="170"></el-table-column>
        <el-table-column prop="tenderOfficer" label="招标负责人" width="90"></el-table-column>
        <el-table-column label="操作" width="170">
          <template slot-scope="scope">
            <el-button type="success" @click="handleLook(scope.row)">查看</el-button>
            <el-button type="primary" v-if="scope.row.enrollStatus === false" @click="handleEnlists(scope.row)">报名</el-button>
            <el-button type="danger" v-else-if="scope.row.enrollStatus === true">已报名</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="padding: 10px 0;margin-left: 800px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 15, 20,30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
<!--    查看-->
    <el-dialog :visible.sync="dialogLookVisible"
               style="text-align: center;"
               width="1000"
    >
      <div class="dialog-title" style="margin-top: -40px">{{ lookForm.dialogTitle }}</div>
      <el-descriptions title="" style="display: inline-block;" column="4" size="mini">
        <el-descriptions-item label="项目预算（万元）">{{lookForm.budget}}</el-descriptions-item>
        <el-descriptions-item label="采购人">{{ lookForm.applyingDepartment }}</el-descriptions-item>
        <el-descriptions-item label="开标时间">{{ lookForm.meetDate }}</el-descriptions-item>
        <el-descriptions-item label="进度">
          <span v-if="lookForm.status === 1">待公告</span>
          <span v-else-if="lookForm.status === 2">已公告</span>
          <span v-else-if="lookForm.status === 3">待公示</span>
          <span v-else-if="lookForm.status === 4">已公示</span>
          <span v-else-if="lookForm.status === 5">已完成</span>
        </el-descriptions-item>
      </el-descriptions>
      <el-card>
        <el-descriptions title="" style="" column="2" size="mini">
          <el-descriptions-item label="投标单位签到时间">{{ getAdjustedMeetDateF30(lookForm.meetDate) }}</el-descriptions-item>
          <el-descriptions-item label="资质审核时间">{{ getAdjustedMeetDateZ30(lookForm.meetDate) }}</el-descriptions-item>
          <el-descriptions-item label="开标时间">{{ lookForm.meetDate }}</el-descriptions-item>
          <el-descriptions-item label="开标地点">{{ lookForm.meetLoca }}</el-descriptions-item>
          <el-descriptions-item label="公告内容">{{lookForm.announcementText}}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-dialog>
<!--    报名-->
    <el-dialog :visible.sync="dialogEnlistsVisible"
               :custom-class="'slide-right-dialog'"
    >
      <div style="border: 2px solid #409EFF; border-radius: 5px; padding: 20px; background-color: #f2f7fc; margin-bottom: 20px;">
        <el-descriptions :title="enlistForm.title" style="display: inline-block;margin-top: -100px" column="4" size="mini">
          <el-descriptions-item label="采购方式">
            {{enlistForm.procurementMethod}}
          </el-descriptions-item>
          <el-descriptions-item label="项目预算（万元）">{{ enlistForm.budget }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="dialog-title"><i class="el-icon-d-arrow-right"></i>我要报名</div>
      <el-card>
        <el-form :model="enlistForm" :rules="rules" :ref="enlistForm" label-width="120px" class="demo-ruleForm custom-form" style="margin-top: 30px">
          <el-form-item label="企业名称" prop="departmentName">
            <el-input v-model="enlistForm.departmentName"></el-input>
          </el-form-item>
          <el-form-item label="法人代表授权书" prop="alrFileUrl">
            <el-upload
                :action="'http://'+serverIp() + ':8081/jdyfy/file/upload'"
                :show-file-list="true"
                :on-success="handleAnnounFile"
                :on-error="handleAnnounFileError"
                :limit="1">
              <el-button size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">请上传不超过50mb的文件，只能上传一个文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="备注说明" prop="adText">
            <el-input type="textarea" v-model="enlistForm.adText"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveEnlists">确定报名</el-button>
            <el-button @click="dialogEnlistsVisible = false">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import {getProjectPageByStatus, getProjectPageByStatusSpace} from "@/api/project"
import {getAdIsHave, getAnnouncementsByProjectNumbers} from "@/api/announcement";
import {addAnnouDepart} from "@/api/department";
import {getMeetByProjectName} from "@/api/meet";
import {serverIp} from "../../../../public/config.js";

export default {
  name: "AnnouncList",
  data() {
    return {
      user: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {},
      procurementMethod:'',
      tableData: [],
      pageNum: 1, //当前页
      pageSize: 10, //每页显示条数
      total: 0, //总条数
      projectNumber: "", //项目编号
      projectName: "", //项目名称
      dialogLookVisible: false,
      dialogEnlistsVisible: false,
      FileUrl: "",
      lookForm: {
        dialogTitle: "",
      },
      announForm: {
        dateRange: [],
        pofc:'西安市小寨西路196号( 西安交通大学第一附属医院行政院区招采办会议室）',
      },
      form: {
        projectNumber: '',
        projectName: '',
        quantity: 1,//数量
        status: 2,
        procurementMethod: '',//采购方式
        procurementType: '',//采购类型
        applicant: '1',//申请人
      },
      enlistForm:{},
    }
  },
  created: function () {
    this.init();
  },
  methods: {
    serverIp() {
      return serverIp
    },
    init() {
      getProjectPageByStatus(this.pageNum, this.pageSize, this.projectNumber, this.projectName, this.procurementMethod, 2, 2)
          .then(res => {
            console.log(res);
            const projects = res.records;
            const projectNumbers = projects.map(project => project.projectNumber);

            getAnnouncementsByProjectNumbers(projectNumbers).then(announcements => {
              const projectPromises = projects.map(async project => {
                const announcement = announcements.find(a => a.projectNumber === project.projectNumber);
                project.announcementName = announcement ? announcement.announcementName : "暂无";
                project.announcementText = announcement ? announcement.announcementText : "暂无";
                const startTime = announcement ? announcement.announcementStartTime : "暂无";
                const endTime = announcement ? announcement.announcementEndTime : "暂无";
                if (startTime && endTime) {
                  project.announDate = `${startTime} - ${endTime}`;
                }

                // 等待异步的报名状态查询完成
                const isEnrolled = await getAdIsHave(announcement.announcementName, this.user.department);
                project.enrollStatus = isEnrolled;

              });

              // 等待所有项目的异步任务完成
              Promise.all(projectPromises).then(() => {
                this.tableData = projects;
                this.total = res.total;
              });
            });
          });
    },
    getAdjustedMeetDateF30(meetDate) {
      if(meetDate === '暂无'){
        return '暂无'
      }
      // 如果 meetDate 是字符串，首先将它转换为 Date 对象
      let date = new Date(meetDate);
      // 将时间提前半小时
      date.setMinutes(date.getMinutes() - 30);
      // 返回格式化后的时间（这里使用 toLocaleString 作为示例）
      return date.toLocaleString();
    },
    getAdjustedMeetDateZ30(meetDate) {
      if(meetDate === '暂无'){
        return '暂无'
      }
      // 如果 meetDate 是字符串，首先将它转换为 Date 对象
      let date = new Date(meetDate);
      // 将时间提前半小时
      date.setMinutes(date.getMinutes() + 30);
      // 返回格式化后的时间（这里使用 toLocaleString 作为示例）
      return date.toLocaleString();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.init();
    },
    async handleLook(row) { //查看
      console.log(row)
      this.lookForm = row
      this.lookForm.dialogTitle = `${row.projectName}(招标项目编号：${row.projectNumber})`
      await getMeetByProjectName(row.projectName).then(res => {
        console.log(res)
        this.lookForm.meetDate = res ? res.meetTime : "暂无";
        this.lookForm.meetLoca = res ? res.meetLoca : "暂无";
      })
      this.dialogLookVisible = true
    },
    handleEnlists(row){ //点击报名
      this.enlistForm.title = `${row.projectName}（招标项目编号${row.projectNumber}）`
      this.enlistForm.budget = row.budget
      this.enlistForm.procurementMethod = row.procurementMethod
      this.enlistForm.departmentName = JSON.parse(localStorage.getItem('user')).department
      this.enlistForm.announcementName = row.announcementName
      this.dialogEnlistsVisible = true
    },
    saveEnlists(){ //确定报名
      addAnnouDepart(this.enlistForm).then(res => {
        if (res) {
          this.enrollStatus = true
          this.$message({
            type: 'success',
            message: '报名成功'
          })
          this.dialogEnlistsVisible = false
        }
      })
    },
    handleAnnounFile(row){ //公告附件，row为公告文件附件下载路径
      this.enlistForm.alrFileUrl = row
      this.$message.success('文件添加成功')
    },
    handleAnnounFileError(err, file, fileList) { //公告附件上传失败提示
      // 上传失败的处理逻辑
      this.$message.error('文件上传失败，请重试');
    },
    reset() {
      this.projectNumber = ''
      this.projectName = ''
      this.init();
    },
  }
}
</script>

<style scoped>
>>> .slide-right-dialog {
  top: -150px;
  right: 0;
  margin: 0;
  position: absolute;
  height: 1000px;
  width: 600px;
  animation: slide-right 0.3s ease;
}
>>> .slide-right-dialog .el-dialog__title {
  font-size: 14px; /* 调整对话框正文内容的字体大小 */
}
</style>
